import 'package:coinbaby/common/const/cosnt.dart';
import 'package:dio/dio.dart';

enum HTTPMETHOD {
   GET,
   POST,
   PUT,
   DELETE
}

class Networktool {

  static String baseURL = AppConst.APP_IS_RELEASE ? "https://api.zhaotaa.com/" : "http://192.168.0.111/";
  static request(
    String url,
    {
      HTTPMETHOD method = HTTPMETHOD.POST,
      Map<String, dynamic> params,
      Function success, 
      Function(String msg) fail,
      Function finaly
    }) async {
    
    Response response;
    url = baseURL + url;
    print("api = $url, param = $params, method:$method");

    // SharedPreferences share = await SharedPreferences.getInstance();
    // String token = share.getString(KEY_user_token);

    Options options = Options(receiveTimeout: 1000000);
    // if(token != null){
    //   print("token = $token");
    //   options = Options(
    //     headers: {"token": token}
    //   );
    // }

    try {
      switch (method) {
        case HTTPMETHOD.POST:
          FormData formData = FormData.fromMap(params);
          response = await Dio().post(url, data: formData, options: options);
          break;
        case HTTPMETHOD.GET:
          if(params == null) params = {};
          response = await Dio().get(url, queryParameters: params, options: options);
          break;
        case HTTPMETHOD.PUT:
          response = await Dio().put(url, data: params, options: options);
          break;
        case HTTPMETHOD.DELETE:
          response = await Dio().delete(url, data: params,options: options);
          break;
        default:
      }
    } catch (e) {
      if(finaly != null) finaly();
      print(e.toString());
      if(fail != null)fail(e.toString());
    }
    

    if(finaly != null) finaly();
    print("url = $url, data = ${response.data}");
    String code = response.headers.value("statuscode").toString();
    if(code == "200" || code == null) {
      if(success != null) success(response.data);
    } else {
      if(fail != null) {
        if(response.data is Map) {
          fail(response.data["msg"].toString());
        } else {
          fail(response.toString());
        }
      }
    }
  }

  // 下载图片到本地
  static downloadImage(String url, {Function(dynamic) success}) async {
    var response = await Dio().get(url, options: Options(responseType: ResponseType.bytes));
    if(success != null) success(response.data);
  }
}